package com.zip.filemanager;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.zip.z4player.R;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


public class FileFragment extends Fragment {
    final String Tag = "FileFragment_Tag";
    final String STORAGE_PATH = "/storage";
    final File EXT_PATH_FILE = Environment.getExternalStorageDirectory();
    File NowPath = null;
    //获取保存所有储存设备
    List<File> storage = new ArrayList<>();
    List<File> data = new ArrayList<File>();
    FileListAdapter adapter;

    ListView mListView;

    FragmentCallBackValue callBackValue;

    public FileFragment() {
    }

    //region onAttach回调(Fragment传值给Activity)
    // fragment与activity产生关联是  回调这个方法
    //api<23时调用onAttach(Activity activity) 否则调用onAttach(Context):

    /*
    * onAttach(Context) is not called on pre API 23 versions of Android and onAttach(Activity) is deprecated
    * Use onAttachToContext instead
    */
    @TargetApi(23)
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        onAttachToContext(context);
    }

    /*
     * Deprecated on API 23
     * Use onAttachToContext instead
     */
    @SuppressWarnings("deprecation")
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            onAttachToContext(activity);
        }
    }

    /*
     * Called when the fragment attaches to the context
     */
    protected void onAttachToContext(Context context) {
        //do something
        callBackValue = (FragmentCallBackValue) getActivity();

    }

    //endregion
    //定义回调接口
    public interface FragmentCallBackValue {
        void FrameLayoutShow(int id, boolean show);

        void ReturnVideoPath(File path);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        final View view = inflater.inflate(R.layout.fragment_file, container, false);

        //region 获取Activity传来的值
//        Bundle bundle = getArguments();
//        if (bundle != null) {
//            if (bundle.getString("path") != null) {
//                Log.d(Tag, "bundle:" + bundle.getString("path"));
//                NowPath = new File(bundle.getString("path"));
//            }else if(bundle.getString("path") != null) {
//                Log.d(Tag, "bundle:" + bundle.getString("path"));
//                NowPath = new File(bundle.getString("path"));
//            }
//        }
        //endregion

        //region 获取储存设备路径
        storage.clear();
        storage.add(EXT_PATH_FILE);
        File[] files = new File("/storage").listFiles();
        for (final File file : files) {
            if (file.canRead()) {
                Log.d(Tag, "获取到路径:" + file.getName());
                storage.add(file);
            }
        }
        //endregion

        Button button = ((Button) view.findViewById(R.id.button1));
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                callBackValue.FrameLayoutShow(id, false);
//                getPath(NowPath.getParent());
            }
        });


        mListView = (ListView) view.findViewById(R.id.lv);
        adapter = new FileListAdapter(getContext(), data);
        mListView.setAdapter(adapter);
        if (NowPath == null) {
            NowPath = new File(STORAGE_PATH);
        }
        getPath(NowPath);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (data.get(i).isDirectory()) {
                    //如果是文件夹
                    getPath(data.get(i));
                } else {
                    callBackValue.ReturnVideoPath((File) data.get(i));
                }
            }
        });


        return view;
    }


    private void getPath(String path) {
        getPath(new File(path));
    }

    private void getPath(File file) {
//        Toast.makeText(getContext(), file.getPath(), Toast.LENGTH_SHORT).show();
        Log.d(Tag, "get File:" + file.getPath() + ":" + EXT_PATH_FILE.getParent());
        NowPath = file;
        data.clear();
        if (NowPath.getPath().equals(STORAGE_PATH)
                || NowPath.getPath().equals(EXT_PATH_FILE.getParent())) {
            for (File f : storage) data.add(f);
        } else {
            data.add(NowPath.getParentFile());
            File[] files = NowPath.listFiles();
            for (File f : files) data.add(f);
        }
        adapter.notifyDataSetChanged();
        mListView.setSelection(0);
    }

    class FileListAdapter extends BaseAdapter {

        private Context context;
        private List mdata;
        private LayoutInflater inflater;

        public FileListAdapter(Context context, List data) {
            this.context = context;
            this.mdata = data;
            initLayoutInflater();
        }

        void initLayoutInflater() {
            inflater = LayoutInflater.from(context);
        }

        public int getCount() {
            return mdata.size();
        }

        public Object getItem(int position) {
            return mdata.get(position);
        }

        public long getItemId(int position) {
            return 0;
        }

        public View getView(int position1, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            View view = null;
            final int position = position1;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.list_item_file, null);
                holder = new ViewHolder();
                holder.FileName = (TextView) convertView.findViewById(R.id.tv_file_name);
                holder.FileSize = (TextView) convertView.findViewById(R.id.tv_file_size);
                holder.FileModifiedDtae = (TextView) convertView.findViewById(R.id.tv_file_modified_date);
                convertView.setTag(holder);
            } else {
                view = convertView;
                holder = (ViewHolder) view.getTag();
            }


            try {
                File file = (File) mdata.get(position);
                if (position == 0 && !NowPath.getPath().equals(EXT_PATH_FILE.getParent()) && !NowPath.getPath().equals(STORAGE_PATH)) {

                    //   if (position == 0 && !storage.contains(file) && (mdata.size() < 2 || !file.getParent().equals(((File) mdata.get(1)).getParent()))) {
                    holder.FileName.setText("返回上一级");
                    holder.FileSize.setText("");
                    holder.FileModifiedDtae.setText("");
                } else {
                    holder.FileName.setText(file.getName());
                    if (file.isDirectory()) {
                        File[] files = file.listFiles();
                        holder.FileSize.setText(files.length + "项");
                    } else
                        holder.FileSize.setText(getFileSize(file.length()));
                    holder.FileModifiedDtae.setText(getTimeFromMillisecond(file.lastModified(), "yyyy/M/d HH:mm"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return convertView;
        }

        public int getID(int position) {
            return (Integer) ((Map<String, Object>) mdata.get(position)).get("ID");
        }

        class ViewHolder {
            TextView FileName;
            TextView FileSize;
            TextView FileModifiedDtae;
        }


        //region 从时间(毫秒)中提取出时间

        private String getTimeFromMillisecond(Long millisecond, String format) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
            Date date = new Date(millisecond);
            String timeStr = simpleDateFormat.format(date);
            return timeStr;
        }

        //endregion
        //region 文件大小处理
        private String getFileSize(Long fSize) {
            DecimalFormat df = new DecimalFormat("#.00");
            String fileSizeString = "";
            if (fSize < 1024) {
                fileSizeString = df.format((double) fSize) + "B";
            } else if (fSize < 104875) {
                fileSizeString = df.format((double) fSize / 1024) + "KB";
            } else if (fSize < 1073741824) {
                fileSizeString = df.format((double) fSize / 104875) + "MB";
            } else {
                fileSizeString = df.format((double) fSize / 1073741824) + "GB";
            }
            return fileSizeString;
        }
        //endregion
    }


}
